package com.ipzoe.common.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * StringUtil
 * <p>
 * Created 2018/01/19.
 *
 * @author pfzhang
 */
public class StringUtil {

    public static final char UNDERLINE = '_';

    /**
     * 检查字符串是否为空,为空返回false,不为空返回true
     *
     * @param word 字符串
     * @return 为空返回false, 不为空返回true
     */
    public static boolean isNotEmpty(String word) {
        return null != word && !"".equals(word.trim());
    }

    /**
     * 将String时间格式转为LocalDateTime
     * <p>
     * String时间格式为 yyyy-MM-dd HH:mm:ss
     *
     * @param time String时间格式
     * @return LocalDateTime
     */
    public static LocalDateTime string2LocalDateTime(String time) {
        if (isNotEmpty(time)) {
            return LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
        return null;
    }

    /**
     * 驼峰 -> 下划线
     *
     * @param param 字符串(驼峰写法)
     * @return 字符串(下划线写法)
     */
    public static String camelToUnderline(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append(UNDERLINE);
                sb.append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 下划线 -> 驼峰
     *
     * @param param 字符串(下划线写法)
     * @return 字符串(驼峰写法)
     */
    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 首字母小写
     *
     * @param name 字符串
     * @return 首字母小写后的字符串
     */
    public static String initialCase(String name) {
        name = name.substring(0, 1).toLowerCase() + name.substring(1);
        return name;
    }
}
